package cn.toleo.content.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.toleo.common.pojo.EasyUITreeNode;
import cn.toleo.common.pojo.ToleoResult;
import cn.toleo.content.service.ContentCategoryService;
import cn.toleo.mapper.TbContentCategoryMapper;
import cn.toleo.pojo.TbContentCategory;
import cn.toleo.pojo.TbContentCategoryExample;
import cn.toleo.pojo.TbContentCategoryExample.Criteria;

@Service
public class ContentCategoryServiceImpl implements ContentCategoryService {
		
	@Autowired
	private TbContentCategoryMapper contentCategoryMapper;
	
	@Override
	public List<EasyUITreeNode> getContentCategoryList(long parentId){
		//根据parentId查询字节点列表
		TbContentCategoryExample example = new TbContentCategoryExample();
		//设置查询条件
		Criteria criteria = example.createCriteria();
		criteria.andParentIdEqualTo(parentId);
		//执行查询
		List<TbContentCategory> list = contentCategoryMapper.selectByExample(example);
		List<EasyUITreeNode> resultList = new ArrayList<>();
		for (TbContentCategory t:list){
			EasyUITreeNode node = new EasyUITreeNode();
			node.setText(t.getName());
			node.setId(t.getId());
			node.setText(t.getIsParent()?"open":"close");
			resultList.add(node);
		}
		return resultList;
	}

	@Override
	public ToleoResult addContentCategory(Long parentId, String name) {
		//创建pojo对象
		TbContentCategory contentCategory = new TbContentCategory();
		//补全对象属性
		contentCategory.setParentId(parentId);
		contentCategory.setName(name);
		//状态。可选值:1(正常),2(删除)
		contentCategory.setStatus(1);
		//排序
		contentCategory.setSortOrder(1);
		contentCategory.setIsParent(false);
		contentCategory.setCreated(new Date());
		contentCategory.setUpdated(new Date());
		//插入数据库
		contentCategoryMapper.insert(contentCategory);
		//判断父节点状态
		TbContentCategory parent = contentCategoryMapper.selectByPrimaryKey(parentId);
		if(!parent.getIsParent()){
			//父节点应该为父节点则改变
			parent.setIsParent(true);
			//更新父节点
			contentCategoryMapper.updateByPrimaryKey(parent);
			
		}
		//返回结果
		return ToleoResult.ok(contentCategory);
	}
	
}
